

import 'package:flutter/cupertino.dart';
import 'package:isar/isar.dart';
import 'package:path_provider/path_provider.dart';


//  flutter pub run build_runner build 生成
import 'isar_key_value_model.dart';

class DatabaseManager {
  static DatabaseManager? _instance;

  static DatabaseManager getInstance() {
    _instance ??= DatabaseManager._internal();
    return _instance!;
  }

  DatabaseManager._internal();

  Isar? isar;

  ///初始化/data/app/com.sunda数据库
  Future<void> initDb() async {
    try {
      final dir = await getApplicationDocumentsDirectory();
      print(dir.path);
      isar = await Isar.open([
        IsarKeyValueModelSchema,
      ], directory: dir.path, name: 'vosa-db');
    } catch (e, s) {
      print("数据库启动失败");
      debugPrintStack(label:e.toString(),stackTrace: s);
    }
  }

  ///写入或者修改数据库
  Future<void> saveData(Function() fun) async {
    try {
      await isar?.writeTxn(() async {
        await fun();
      });
    } catch (e, s) {
      debugPrintStack(label:e.toString(),stackTrace: s);
    }
  }
}